<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="角色名称" prop="roleName">
              <el-input v-model="queryParams.roleName" placeholder="请输入角色名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['shop:shopRole:add']">新增</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table border v-loading="loading" :data="shopRoleList">
        <el-table-column label="角色名称" align="center" prop="roleName" />
<!--        <el-table-column label="角色权限标志" align="center" prop="roleKey" />-->
        <el-table-column label="角色状态" align="center">
          <template #default="scope">
            <dict-tag :options="sys_normal_disable" :value="scope.row.roleStatus" />
          </template>
        </el-table-column>
        <el-table-column label="角色排序" align="center" prop="roleSort" />
<!--        <el-table-column label="权限类型" align="center" prop="shopAuthType">-->
<!--          <template #default="scope">-->
<!--            <dict-tag :options="shop_auth_type" :value="scope.row.shopAuthType" />-->
<!--          </template>-->
<!--        </el-table-column>-->
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top" v-if="scope.row.shopAuthType != '1'">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['shop:shopRole:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top" v-if="scope.row.shopAuthType != '1'">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['shop:shopRole:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改店铺角色对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="shopRoleFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="form.roleName" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="状态" prop="roleStatus">
          <el-radio-group v-model="form.roleStatus">
            <el-radio v-for="(dict, index) in sys_normal_disable" :key="index" :value="dict.value">{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="角色排序" prop="roleSort">
          <el-input-number
            v-model="form.roleSort"
            controls-position="right"
            placeholder="请输入角色排序"
            :min="0"
            :precision="0"
            style="width: 100%"/>
        </el-form-item>
        <el-form-item label="菜单权限">
          <el-checkbox v-model="menuExpand" @change="handleCheckedTreeExpand($event, 'menu')">展开/折叠</el-checkbox>
          <el-checkbox v-model="menuNodeAll" @change="handleCheckedTreeNodeAll($event, 'menu')">全选/全不选</el-checkbox>
          <el-checkbox v-model="menuCheckStrictly" @change="handleCheckedTreeConnect($event, 'menu')">父子联动</el-checkbox>
          <el-tree
            ref="menuRef"
            class="tree-border"
            :data="menuOptions"
            show-checkbox
            node-key="id"
            :check-strictly="!menuCheckStrictly"
            empty-text="加载中，请稍候"
            :props="{ label: 'label', children: 'children' }"
          ></el-tree>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="ShopRole" lang="ts">
import { listShopRole, getShopRole, delShopRole, addShopRole, updateShopRole, treeselect as menuTreeselect } from '@/api/system/shopRole';
import { ShopRoleVO, ShopRoleQuery, ShopRoleForm } from '@/api/system/shopRole/types';
import { MenuTreeOption, RoleMenuTree } from '@/api/system/menu/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { shop_auth_type, sys_normal_disable } = toRefs<any>(proxy?.useDict('shop_auth_type', 'sys_normal_disable'));

const shopRoleList = ref<ShopRoleVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const menuOptions = ref<MenuTreeOption[]>([]);
const menuExpand = ref(false);
const menuNodeAll = ref(false);
const menuCheckStrictly = ref(true);
const menuRef = ref<ElTreeInstance>();


const queryFormRef = ref<ElFormInstance>();
const shopRoleFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: ShopRoleForm = {
  id: undefined,
  shopId: undefined,
  roleName: undefined,
  roleKey: undefined,
  roleStatus: undefined,
  roleSort: undefined,
  shopAuthType: undefined,
  shopMenuIdList: [],
}
const data = reactive<PageData<ShopRoleForm, ShopRoleQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    shopId: undefined,
    roleName: undefined,
    roleKey: undefined,
    roleStatus: undefined,
    roleSort: undefined,
    shopAuthType: undefined,
    params: {
    }
  },
  rules: {
    id: [
      { required: true, message: "主键ID不能为空", trigger: "blur" }
    ],
    shopId: [
      { required: true, message: "店铺ID不能为空", trigger: "blur" }
    ],
    roleName: [
      { required: true, message: "角色名称不能为空", trigger: "blur" }
    ],
    roleKey: [
      { required: true, message: "角色权限标志不能为空", trigger: "blur" }
    ],
    roleStatus: [
      { required: true, message: "角色状态不能为空", trigger: "change" }
    ],
    roleSort: [
      { required: true, message: "角色排序不能为空", trigger: "blur" }
    ],
    shopAuthType: [
      { required: true, message: "店铺权限类型【1：店铺超管   2：普通管理员】不能为空", trigger: "change" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询店铺角色列表 */
const getList = async () => {
  loading.value = true;
  const res = await listShopRole(queryParams.value);
  shopRoleList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  menuRef.value?.setCheckedKeys([]);
  menuExpand.value = false;
  menuNodeAll.value = false;
  form.value = {...initFormData};
  shopRoleFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加店铺角色";
  getMenuTreeselect();
}

/** 修改按钮操作 */
const handleUpdate = async (row?: ShopRoleVO) => {
  reset();
  await getMenuTreeselect();
  const _id = row?.id || ids.value[0]
  const res = await getShopRole(_id);
  Object.assign(form.value, res.data);
  setTimeout(() => {
    res.data.shopMenuIdList.forEach((v) => {
      nextTick(() => {
        menuRef.value?.setChecked(v, true, false);
      });
    });
  }, 500);
  dialog.visible = true;
  dialog.title = "修改店铺角色";
}

/** 所有菜单节点数据 */
const getMenuAllCheckedKeys = (): any => {
  // 目前被选中的菜单节点
  let checkedKeys = menuRef.value?.getCheckedKeys();
  // 半选中的菜单节点
  let halfCheckedKeys = menuRef.value?.getHalfCheckedKeys();
  if (halfCheckedKeys) {
    checkedKeys?.unshift.apply(checkedKeys, halfCheckedKeys);
  }
  return checkedKeys;
};

/** 提交按钮 */
const submitForm = () => {
  shopRoleFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      form.value.shopMenuIdList = getMenuAllCheckedKeys();
      if (form.value.id) {
        await updateShopRole(form.value).finally(() =>  buttonLoading.value = false);
      } else {
        await addShopRole(form.value).finally(() =>  buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: ShopRoleVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除店铺角色编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
  await delShopRole(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 查询菜单树结构 */
const getMenuTreeselect = async () => {
  const res = await menuTreeselect();
  menuOptions.value = res.data;
};

/** 树权限（展开/折叠）*/
const handleCheckedTreeExpand = (value: boolean, type: string) => {
  let treeList = menuOptions.value;
  for (let i = 0; i < treeList.length; i++) {
    if (menuRef.value) {
      menuRef.value.store.nodesMap[treeList[i].id].expanded = value;
    }
  }
};
/** 树权限（全选/全不选） */
const handleCheckedTreeNodeAll = (value: any, type: string) => {
  menuRef.value?.setCheckedNodes(value ? (menuOptions.value as any) : []);
};
/** 树权限（父子联动） */
const handleCheckedTreeConnect = (value: any, type: string) => {
  menuCheckStrictly.value = value;
};
onMounted(() => {
  getList();
});
</script>
